#ifndef __VALOG_FILE_LOGAPPENDER_H__
#define __VALOG_FILE_LOGAPPENDER_H__

#include "../logformatter.h"
#include "../mutext.h"
#include "logappender.h"
#include <chrono>
#include <condition_variable>
#include <filesystem>
#include <fstream>
#include <mutex>
#include <pthread.h>
#include <sys/mman.h>
#include <thread>
#include <vector>

constexpr uint64_t g_ulLogFileSize = 10 * 1024 * 1024;
namespace fs = std::filesystem;

namespace vlog
{

class FileLogAppender : public LogAppender
{
    public:
    explicit FileLogAppender(const std::string& strFileName);
    ~FileLogAppender();
    void WriteLog(event::LogEvent::ptr pEvent) override final;
    void RealyWriteLog(event::LogEvent::ptr pEvent);
    void FlashLog();

    private:
    bool ReOpen() noexcept;
    void CheckLastOpen() noexcept;

    private:
    std::string m_FileName;
    fs::path m_FilePath;
    std::ofstream m_FileStream;

    bool m_isOpenError = false;
    std::chrono::time_point<std::chrono::system_clock> m_LastOpen; // 上一次打开的时间点

    bool m_isFlash = false;
    // CASMutex m_mutex;
    std::mutex m_mutex;
    std::thread m_Flashlogthread;
    std::condition_variable_any m_ConditionVariable;
    std::vector<event::LogEvent::ptr> m_CurEventBuf;
    std::vector<std::vector<event::LogEvent::ptr>> m_EventBufs;
};

} // namespace vlog

#endif